package es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.plain.actions;

import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import es.udc.fbellas.j2ee.tiendaweb.model.usuario.TO.UsuarioProfileTO;
import es.udc.fbellas.j2ee.tiendaweb.model.usuario.DAO.SQLUsuarioProfileDAO;
import es.udc.fbellas.j2ee.tiendaweb.model.usuario.DAO.SQLUsuarioProfileDAOFactory;
import es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.util.PasswordEncrypter;
import es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.exceptions.IncorrectPasswordException;
import es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.TO.LoginResultTO;

public class LoginAction implements NonTransactionalPlainAction {

    private String loginName;
    private String password;
    private boolean passwordIsEncrypted;

    public LoginAction(String loginName, String password, 
        boolean passwordIsEncrypted) {    
        
        this.loginName = loginName;
        this.password = password;
        this.passwordIsEncrypted = passwordIsEncrypted;

    }
    
    /**
     *
     * @return a <code>LoginResultTO</code>
     */
    public Object execute(Connection connection) 
        throws IncorrectPasswordException, InstanceNotFoundException, 
            InternalErrorException {
                
        SQLUsuarioProfileDAO usuarioProfileDAO = SQLUsuarioProfileDAOFactory.getDAO();
        UsuarioProfileTO usuarioProfileTO = usuarioProfileDAO.find(connection, 
            loginName);
        String storedPassword = usuarioProfileTO.getEncryptedPassword();

        if (passwordIsEncrypted) {
            if (!password.equals(storedPassword)) {
                throw new IncorrectPasswordException(loginName);
            }
        } else {
            if (!PasswordEncrypter.isClearPasswordCorrect(password,storedPassword)) {
        		throw new IncorrectPasswordException(loginName);
            }
        } 

        return new LoginResultTO(
            usuarioProfileTO.getNombre(), 
            storedPassword,usuarioProfileTO.getLanguage(), usuarioProfileTO.getCountry());

    }
    
    /* 
     * This class is tested by
     * "es.udc.fbellas.j2ee.miniportal.model.userfacade.delegate.
     * UserFacadeDelegateFactory".
     */    

}
